let userId = "";
let name = "";
const db = wx.cloud.database();
const _ = db.command;
let EN = new Map();
// pages/mine/mine.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    nickName: '',
    avatarUrl: '',
    userDisplay: 0,
    loginDisplay: 1,
    encounters: [],
    content: "",
    contentName: "",
    contentDate: "",
    contentAddress: "中国",
    contentId: "",
    comments: [],
    commentsDisplay: false,
    contentImageDisplay:false,
    contentImage:""
  },

  onCommentsHideClick() {
    this.setData({
      commentsDisplay: 0,
      comments: []
    })
  },

  onEncounterClick(e) {
    wx.showLoading({
      title: '加载评论中……'
    });
    let i = e.currentTarget.dataset.index;
    let encounters = this.data.encounters;
    let item = encounters[i];
    encounters[i].isNew = false;
    wx.cloud.callFunction({
      name: 'updateSubscription',
      data: {
        encounterId: item._id,
        userId: userId
      }
    });
    this.setData({
      encounters: encounters
    });
    this.data.encounters[i];
    this.setData({
      commentsDisplay: 1,
      content: item.content,
      contentImage: item.imagePath,
      contentImageDisplay: item.imagePath != "",
      contentAddress: item.address,
      contentName: item.name,
      contentDate: item.date,
      contentId: item._id,
      commentInput: ""
    });
    let that = this;
    wx.cloud.callFunction({
      name: 'getComments',
      data: {
        id: this.data.contentId
      },
      success(res) {
        let cs = [];
        for (let i of res.result.data) {
          cs.push(i);
        }
        that.setData({
          comments: cs
        });
      },
      complete() {
        wx.hideLoading()
      }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    userId = options.userId;
    const _ = db.command;
    db.collection("userInfo")
      .where({
        userId: _.eq(userId)
      })
      .get()
      .then(res => {
        if (res.data.length != 0)
          name = res.data[0].name;
        else
          this.setData({
            isLogin: true
          })
      })
  },
  bindGetUserInfo: function (e) {
    this.setData({
      avatarUrl: e.detail.userInfo.avatarUrl,
      nickName: e.detail.userInfo.nickName,
      userDisplay: 1,
      loginDisplay: 0,
      encounters: null
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  getDateString(date) {
    date = new Date(date);
    return date.getFullYear() + "年" + (date.getMonth() + 1) + "月" + date.getDate() + "日";
  },
  onReady: function () {
    let that = this;
    wx.cloud.callFunction({
        name: 'getSubscription',
        data: {
          userId: userId
        },
        success(res) {
          let es = [];
          for (let i of res.result.data) {
            //获取数据库命令对象
            let isNew = i.isNew;
            db.collection("encounters").where({
                _id: _.eq(i.encounterId),
              })
              .limit(1)
              .get()
              .then(res => {
                if(res.data.length == 0)
                  return;
                res.data[0].date = that.getDateString(res.data[0].date);
                es.push({
                  ...res.data[0],
                  isNew
                })
                that.setData({
                  encounters: es
                });
              })
              .catch(err => {
                console.error(err)
              })
          }
        }
      })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },
  postCommentInput(e) {
    this.setData({
      commentInput: e.detail.value
    })
  },
  postComment(e) {
    let str = this.data.commentInput.trim();
    if (str == "") {
      wx.showToast({
        title: '内容不能为空哦！',
        icon: 'error',
        duration: 1500
      })
      this.setData({
        commentInput: str
      })
      return;
    }
    wx.showLoading({
      title: '评论中……'
    });
    let that = this;
    wx.cloud.callFunction({
      name: 'addComment',
      data: {
        userName: name,
        id: that.data.contentId,
        content: str
      },
      success(res) {
        //更新评论
        let cs = that.data.comments;
        cs.push({
          content: str,
          userName: name
        });
        that.setData({
          comments: cs,
          commentInput: ""
        })
        //更新其他用户的消息状态
        wx.cloud.callFunction({
          name: 'newSubscription',
          data: {
            encounterId: that.data.contentId,
            userId: userId,
            isNew: true
          }
        });
      },
      complete() {
        wx.hideLoading()
      }
    })
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})